package com.zhongwang.mms.module.jiaGongSemi.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.HInventory;
import com.zhongwang.mms.gen.entity.HOrder;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.half.model.HInBillModel;
import com.zhongwang.mms.module.half.model.HOrderDetailModel;
import com.zhongwang.mms.module.half.model.PrintListModel;
import com.zhongwang.mms.module.half.service.HBasicService;
import com.zhongwang.mms.module.jiaGongSemi.dao.SemiInDao;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemi;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiDetail;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiInBillModel;
import com.zhongwang.mms.module.jiaGongSemi.model.JSemiInventory;
import com.zhongwang.mms.module.jiaGongStorage.dao.StorageStockQueryDao;
import com.zhongwang.mms.module.jiaGongStorage.model.JStorageInventory;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurlnvQueryDao;
import com.zhongwang.mms.module.purchase.model.PChangeOrderModel;
import com.zhongwang.mms.module.purchase.model.VWProject;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ExportExcelUtils;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import lombok.var;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName： AllocationManageService
 * @Description： 库存查询业务逻辑层
 * @Author： China.zh
 * @Date： 2020/4/6 13:41
 * @Version： V1.0
 **/
@Log4j2
@Service
public class SemiInService {


    @Autowired
    private LogService logService;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private SemiInDao semiInDao;
    @Autowired
    private BoardService boardService;
    @Autowired
    private  HBasicService basicService;

    /**
     * 获取外协件库房
     *
     * @return
     */
    public List<TWarehouseInfo> getWarInfo() {

        return semiInDao.getWarInfo();
    }

    @Transactional
    public JsonResult saveSemiBillModel(JSemiInBillModel jSemiInBillModel) {

        JsonResult jsonResult = new JsonResult();
        List<String> result = new ArrayList<>();
        PrintListModel printListModel = new PrintListModel();
        //验证物料描述、数量、单位是否为空
        for (var i = 0; i < jSemiInBillModel.getInsertData().size(); i++) {
            if (jSemiInBillModel.getInsertData().get(i).getOdaMatName() == null || jSemiInBillModel.getInsertData().get(i).getOdaMatName() == "") {
                result.add("\n第" + (i + 1) + "行" + " 物料描述 为空");
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaAvaNum() == null) {
                result.add("\n第" + (i + 1) + "行" + " 数量 为空");
            } else if (jSemiInBillModel.getInsertData().get(i).getOdaAvaNum() <= 0) {
                result.add("\n第" + (i + 1) + "行" + " 数量 必须大于0");
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaUnit() == null || jSemiInBillModel.getInsertData().get(i).getOdaUnit() == "") {
                result.add("\n第" + (i + 1) + "行" + " 单位 为空");
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaOutsourcedTypeName() == null || jSemiInBillModel.getInsertData().get(i).getOdaOutsourcedTypeName() == "") {
                result.add("\n第" + (i + 1) + "行" + " 外协件类别 为空");
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaStockTypeName() == null || jSemiInBillModel.getInsertData().get(i).getOdaStockTypeName() == "") {
                result.add("\n第" + (i + 1) + "行" + " 在库类型 为空");
            } else if (jSemiInBillModel.getInsertData().get(i).getOdaStockTypeName().equals("项目在库") && (jSemiInBillModel.getInsertData().get(i).getOdaProCode() == null || jSemiInBillModel.getInsertData().get(i).getOdaProCode() == "")) {
                result.add("\n第" + (i + 1) + "行" + " 项目编号 为空");
            }
            if ((jSemiInBillModel.getInsertData().get(i).getOdaProCode() != null && jSemiInBillModel.getInsertData().get(i).getOdaProCode() != "") && (jSemiInBillModel.getInsertData().get(i).getOdaProName() == null || jSemiInBillModel.getInsertData().get(i).getOdaProName() == "")) {
                result.add("\n第" + (i + 1) + "行" + " 项目名称 为空");
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaProCode() != null &&
                    jSemiInBillModel.getInsertData().get(i).getOdaProCode() != "") {
                if (boardService.isNotExist(boardService.projectCodeHandle(jSemiInBillModel.getInsertData().get(i).getOdaProCode()))) {
                    result.add("\n第" + (i + 1) + "行" + " 项目编码不存在 请修改");
                } else {
                    VWProject vmProject = boardService.getVWProjectByProjectCode(boardService.projectCodeHandle(jSemiInBillModel.getInsertData().get(i).getOdaProCode()));
                    if (!vmProject.getName().equals(jSemiInBillModel.getInsertData().get(i).getOdaProName())) {
                        result.add("\n第" + (i + 1) + "行" + " 项目项目名称不正确 请修改");
                    }
                }
            }
            if (jSemiInBillModel.getInsertData().get(i).getOdaProCode() != null && StringUtils.isContainChinese(jSemiInBillModel.getInsertData().get(i).getOdaProCode())) {
                result.add("\n第" + (i + 1) + "行" + " 项目编码不可出现汉字 违规字符");
            }
        }
        if (result.size() > 0) {
            result.add("\n单据保存失败，请先维护以上信息！");
            printListModel.setList(result);
            printListModel.setId(jSemiInBillModel.getFormData().getOdrId());
            jsonResult.setData(printListModel);
            return jsonResult;
        }
        jSemiInBillModel.getFormData().setOdrType(1);//1入库2出库
        jSemiInBillModel.getFormData().setOdrStatus(0);//1调拨0其他
        //jSemiInBillModel.getFormData().setOdrOutType(1);//采购入库
        //保存主单信息
        JSemi jSemi = saveSemi(jSemiInBillModel);

        JSemiDetail jSemiDetail = new JSemiDetail();
        //遍历表单内容
        for (var i = 0; i < jSemiInBillModel.getInsertData().size(); i++) {

            //获取表单明细
            jSemiDetail = jSemiInBillModel.getInsertData().get(i);
            //获取主单ID
            jSemiDetail.setOdrId(jSemiInBillModel.getFormData().getOdrId());
            //获取仓库
            jSemiDetail.setOdaWhiId(jSemiInBillModel.getFormData().getOdaWhiId());
            //物料分类
            jSemiDetail.setOdaMatType(jSemiInBillModel.getFormData().getOdaMatType());//1是外购件、2是外协件、3是制作件
            //物料编码
            jSemiDetail.setOdaMatCode("1111111111");
            //红冲标识
            jSemiDetail.setOdaRedFlag(0);
            //保存表单明细
            saveJSemiDetail(jSemiDetail);
            //保存库存信息
            saveJSemiInventory(jSemiDetail);

        }
        result.add("单据保存成功！");
        logService.saveLog("【甲供件毛-毛坯库】毛坯入库", "入库单据编码：" + jSemi.getOdrCode());
        printListModel.setList(result);
        printListModel.setId(jSemiInBillModel.getFormData().getOdrId());
        jsonResult.setData(printListModel);
        return jsonResult;
    }

    public JSemi saveSemi(JSemiInBillModel jSemiInBillModel) {
        // 保存入库单主单信息
        JSemi jSemisemi = new JSemi();
        // 获取登入用户实体
        User user = ShiroUtils.getUser();

        jSemisemi = jSemiInBillModel.getFormData();//总单信息
        jSemisemi.setOdrDate(new Date());//制单时间
        jSemisemi.setOdrCode(getInOrderCode());//单据号
        jSemisemi.setOdrTakePerson(user.getName());//制单人
        jSemisemi.setOdrRedFlag(0); //红冲标识
        jSemisemi.setOdrItyFlag(1); //1蓝单2红单

        //保存主单信息
        semiInDao.insertSemi(jSemisemi);

        return jSemisemi;
    }

    //入库单号
    public String getInOrderCode() {
        // 取得当日零时时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date = calendar.getTime();
        // 查询当日是否有入库记录
        List<JSemi> jSemis = semiInDao.findAllByDate(date);
        String orderCode; // 入库单编号生产规则：HRK200317001
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        if (jSemis.size() == 0) {
            orderCode = "HRK" + dateFormat.format(new Date()).substring(2, 8) + "001";
        } else {
            orderCode = "HRK" + dateFormat.format(new Date()).substring(2, 8) + String.format("%03d", Integer.parseInt(jSemis.get(0).getOdrCode().substring(10, 12)) + 1);
        }
        return orderCode;
    }

    public JSemiDetail saveJSemiDetail(JSemiDetail hOrderDetailModel) {

        //保存入库单明细
        JSemiDetail hOrderDetail = new JSemiDetail();

        hOrderDetail.setOdaRushId(hOrderDetailModel.getOdaRushId());//红冲用   生成单据的子单ID
        hOrderDetail.setOdaOdrId(hOrderDetailModel.getOdrId());//获取主单ID
        if (hOrderDetailModel.getOdaSapCode() != null) {
            hOrderDetail.setOdaSapCode(hOrderDetailModel.getOdaSapCode().replace("\n", "").replace(" ", ""));//SAP物料编码
        }
        if (hOrderDetailModel.getOdaMatName() != null) {
            hOrderDetail.setOdaMatName(hOrderDetailModel.getOdaMatName().trim().replace("\n", "").replace(" ", ""));//名称、物料名称
        }
        if (hOrderDetailModel.getOdaMatCode() != null) {
            hOrderDetail.setOdaMatCode(hOrderDetailModel.getOdaMatCode().replace("\n", "").replace(" ", ""));//物料编码
        }
        if (hOrderDetailModel.getOdaDrawingCode() != null) {
            hOrderDetail.setOdaDrawingCode(hOrderDetailModel.getOdaDrawingCode().trim().replace("\n", "").replace(" ", ""));//图号
        }
        hOrderDetail.setOdaNum(hOrderDetailModel.getOdaAvaNum());//数量
        if (hOrderDetailModel.getOdaUnit() != null) {
            hOrderDetail.setOdaUnit(hOrderDetailModel.getOdaUnit().replace("\n", "").replace(" ", ""));//单位
        }
        hOrderDetail.setOdaPrice(hOrderDetailModel.getOdaPrice());//单价
        hOrderDetail.setOdaAmount(hOrderDetailModel.getOdaAmount());
        if (hOrderDetailModel.getOdaTrackCode() != null) {
            hOrderDetail.setOdaTrackCode(hOrderDetailModel.getOdaTrackCode().trim().replace("\n", "").replace(" ", ""));//跟踪号
        }
        if (hOrderDetailModel.getOdaProCode() != null) {
            hOrderDetail.setOdaProCode(boardService.projectCodeHandle(hOrderDetailModel.getOdaProCode()));//项目编号
        }
        if (hOrderDetailModel.getOdaProName() != null) {
            hOrderDetail.setOdaProName(hOrderDetailModel.getOdaProName().trim().replace("\n", "").replace(" ", ""));//项目名称
        }
        hOrderDetail.setOdaPart(hOrderDetailModel.getOdaPart());//部位
        if (hOrderDetailModel.getOdaBrand() != null) {
            hOrderDetail.setOdaBrand(hOrderDetailModel.getOdaBrand().trim().replace("\n", "").replace(" ", ""));//品牌
        }
        hOrderDetail.setOdaMakingPiecesStatus(hOrderDetailModel.getOdaMakingPiecesStatus());//存放状态
        hOrderDetail.setOdaPosition(hOrderDetailModel.getOdaPosition());//区位
        hOrderDetail.setOdaRedFlag(hOrderDetailModel.getOdaRedFlag());//红冲标识
        if (("外购件").equals(hOrderDetailModel.getOdaMatTypeName())) {
            hOrderDetail.setOdaMatType(1);
        } else if (("外协件").equals(hOrderDetailModel.getOdaMatTypeName())) {
            hOrderDetail.setOdaMatType(2);
        } else {
            hOrderDetail.setOdaMatType(hOrderDetailModel.getOdaMatType());
        }
        if(hOrderDetailModel.getOdaWhiId() == null) {
            hOrderDetail.setOdaWhiId(basicService.getWarIdByName(hOrderDetailModel.getOdaWhiIdName()));
        }else {
            hOrderDetail.setOdaWhiId(hOrderDetailModel.getOdaWhiId());
        }
        if (("库存在库").equals(hOrderDetailModel.getOdaStockTypeName())) {
            hOrderDetail.setOdaStockType(1);//在库类型 1是库存在库，2是项目在库
        } else if (("项目在库").equals(hOrderDetailModel.getOdaStockTypeName())) {
            hOrderDetail.setOdaStockType(2);
        } else {
            hOrderDetail.setOdaStockType(hOrderDetailModel.getOdaStockType());
        }
        if (("成品件").equals(hOrderDetailModel.getOdaOutsourcedTypeName())) {
            hOrderDetail.setOdaOutsourcedType(1);
        } else if (("毛坯件").equals(hOrderDetailModel.getOdaOutsourcedTypeName())) {
            hOrderDetail.setOdaOutsourcedType(2);
        }
        hOrderDetail.setOdaRemark(hOrderDetailModel.getOdaRemark());//备注
        hOrderDetail.setOdaStorageDate(hOrderDetailModel.getOdaStorageDate());//入库时间
        hOrderDetail.setOdaCaseNo(hOrderDetailModel.getOdaCaseNo());//箱号
        hOrderDetail.setOdaBoxingDate(hOrderDetailModel.getOdaBoxingDate());//装箱日期
        if (("是").equals(hOrderDetailModel.getOdaIfFinishedProductName())) {
            hOrderDetail.setOdaIfFinishedProduct(1);
        } else if (("否").equals(hOrderDetailModel.getOdaIfFinishedProductName())) {
            hOrderDetail.setOdaIfFinishedProduct(0);
        } else {
            hOrderDetail.setOdaIfFinishedProduct(hOrderDetailModel.getOdaIfFinishedProduct());
        }
        hOrderDetail.setOdaWeight(hOrderDetailModel.getOdaWeight());//重量
        hOrderDetail.setOdaOrderNum(hOrderDetailModel.getOdaOrderNum());//订单号
        hOrderDetail.setOdaTexture(hOrderDetailModel.getOdaTexture());//材质
        hOrderDetail.setOdaSpec(hOrderDetailModel.getOdaSpec());//规格
        hOrderDetail.setOdaOutItyId(hOrderDetailModel.getItyId());
        hOrderDetail.setOdaSupplier(hOrderDetailModel.getOdaSupplier());//供应商
        hOrderDetail.setContractNo(hOrderDetailModel.getContractNo());//合同编号
        //保存入库单明细
        semiInDao.insertJSemiDetail(hOrderDetail);
        hOrderDetailModel.setOdaId(hOrderDetail.getOdaId());
        return hOrderDetailModel;
    }

    /**
     * 入库保存库存信息
     *
     * @param hOrderDetailModel
     * @return
     */
    public JSemiDetail saveJSemiInventory(JSemiDetail hOrderDetailModel) {

        //封装库存信息
        JSemiInventory hInventory = new JSemiInventory();
        hInventory.setItyMatCode("111111111");//系统物料编码
        hInventory.setItyMatName(hOrderDetailModel.getOdaMatName());//物料描述
        if (hOrderDetailModel.getOdaProCode() != null) {
            hInventory.setItyProCode(boardService.projectCodeHandle(hOrderDetailModel.getOdaProCode()));//项目编号
        }
        hInventory.setItyProName(hOrderDetailModel.getOdaProName());//项目名称
        hInventory.setItyPart(hOrderDetailModel.getOdaPart());//部位
        hInventory.setItyNum(hOrderDetailModel.getOdaAvaNum());//在库数量
        hInventory.setItyTrackCode(hOrderDetailModel.getOdaTrackCode());//跟踪号
        hInventory.setItyAvaNum(hOrderDetailModel.getOdaAvaNum());//可用数量
        hInventory.setItyUnit(hOrderDetailModel.getOdaUnit());//单位
        hInventory.setItyPrice(hOrderDetailModel.getOdaPrice());//单价
        hInventory.setItyBrand(hOrderDetailModel.getOdaBrand());//品牌
        hInventory.setItyPosition(hOrderDetailModel.getOdaPosition());//区位
        if (("外购件").equals(hOrderDetailModel.getOdaMatTypeName())) {
            hInventory.setItyMatType(1);
        } else if (("外协件").equals(hOrderDetailModel.getOdaMatTypeName())) {
            hInventory.setItyMatType(2);
        } else {
            hInventory.setItyMatType(hOrderDetailModel.getOdaMatType());
        }
        hInventory.setItyWhiId(hOrderDetailModel.getOdaWhiId());
        if (("库存在库").equals(hOrderDetailModel.getOdaStockTypeName())) {
            hInventory.setItyStockType(1);//在库类型 1是库存在库，2是项目在库
        } else if (("项目在库").equals(hOrderDetailModel.getOdaStockTypeName())) {
            hInventory.setItyStockType(2);
        } else {
            hInventory.setItyStockType(hOrderDetailModel.getOdaStockType());
        }
        if (("成品件").equals(hOrderDetailModel.getOdaOutsourcedTypeName())) {
            hInventory.setItyOutsourcedType(1);
        } else if (("毛坯件").equals(hOrderDetailModel.getOdaOutsourcedTypeName())) {
            hInventory.setItyOutsourcedType(2);
        } else {
            hInventory.setItyOutsourcedType(hOrderDetailModel.getOdaOutsourcedType());
        }
        hInventory.setItyRowNo(hOrderDetailModel.getOdaId());//入库明细ID
        hInventory.setItySapCode(hOrderDetailModel.getOdaSapCode());//SAP物料编码
        hInventory.setItyRemark(hOrderDetailModel.getOdaRemark());//备注
        hInventory.setItyDrawingNumber(hOrderDetailModel.getOdaDrawingCode());//图号
        hInventory.setItyMakingPiecesStatus(hOrderDetailModel.getOdaMakingPiecesStatus());//存放状态
        hInventory.setItyCaseNo(hOrderDetailModel.getOdaCaseNo());//箱号
        hInventory.setItyBoxingDate(hOrderDetailModel.getOdaBoxingDate());//装箱日期
        hInventory.setItyStorageDate(hOrderDetailModel.getOdaStorageDate());//入库日期
        if (("是").equals(hOrderDetailModel.getOdaIfFinishedProductName())) {
            hInventory.setItyIfFinishedProduct(1);
        } else if (("否").equals(hOrderDetailModel.getOdaIfFinishedProductName())) {
            hInventory.setItyIfFinishedProduct(0);
        } else {
            hInventory.setItyIfFinishedProduct(null);
        }//是否成品
        hInventory.setItyWeight(hOrderDetailModel.getOdaWeight());
        hInventory.setItyAvaWeight(hOrderDetailModel.getOdaWeight());
        hInventory.setItyOrderNum(hOrderDetailModel.getOdaOrderNum());
        hInventory.setItyTexture(hOrderDetailModel.getOdaTexture());
        hInventory.setItySpec(hOrderDetailModel.getOdaSpec());
        hInventory.setOdaSupplier(hOrderDetailModel.getOdaSupplier());
        hInventory.setContractNo(hOrderDetailModel.getContractNo());
        semiInDao.insertJSemiInventory(hInventory);
        hOrderDetailModel.setItyId(hInventory.getItyId());
        return hOrderDetailModel;
    }
}
